/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Ventas;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.sql.Statement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author nan
 */
public class medVentasListar implements ActionListener, KeyListener{

    private Conexion.ConexionBD conectar = new Conexion.ConexionBD();
    private ventasListar ventaListar = new ventasListar();
    private Ventas.GUIVenta unaVenta;
    private Ventas.FacturaGUI factura;
    
    private DefaultTableModel dtmVentas;

    public medVentasListar(){
        ventaListar.setLocationRelativeTo(null);
        ventaListar.setActionListeners(this);
        ventaListar.setKeyListener(this);
        ventaListar.setVisible(true);
        ventaListar.getjTextFieldCantidadVentas().setEditable(false);
        ventaListar.getjTextFieldTotalVendido().setEditable(false);
        ventaListar.getjTableVenta().setUpdateSelectionOnSort(false);

        //ventaListar.getjTableVenta().setRowSelectionAllowed(true);
        
        
        actualizarTabla();
    }

    public void actualizarTabla(){
        String[] titulos = {"IDVentas", "Total", "CantArt", "Fecha", "TipoPago", "Nombre Usuario"};
        Object[][] datos = {};
        dtmVentas = new DefaultTableModel(datos, titulos);

        conectar.conectar();
        Statement st;
        try {
            st = conectar.getConn().createStatement();
            String consulta = "SELECT * FROM \"Ventas\"";
            ResultSet rs = st.executeQuery(consulta);
            String id = null;
            while (rs.next()){
                Object[] fila = {rs.getString(1),
                rs.getString(2),
                rs.getString(3),
                rs.getString(4),
                rs.getString(5),
                rs.getString(6)};
                dtmVentas.addRow(fila);
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        getVentaListar().getjTextFieldCantidadVentas().setText("");
        getVentaListar().getjTextFieldTotalVendido().setText("");
        getVentaListar().getjTableVenta().setModel(dtmVentas);
    }
   

    public void actualizarPorFecha(String FechaD,String FechaH){

        String[] titulos = {"IDVentas", "Total", "CantArt", "Fecha", "TipoPago", "Nombre Usuario"};
        Object[][] datos = {};
        dtmVentas = new DefaultTableModel(datos, titulos);
        int cant = 0;
        double total = 0;
        double totalTar = 0;
        double totalCon = 0;
        conectar.conectar();
        Statement st;
        try {
            st = conectar.getConn().createStatement();
            String consulta = "SELECT * FROM \"Ventas\" WHERE \"Fecha\">='"+FechaD+"' AND \"Fecha\" <= '"+FechaH+"';" ;
            ResultSet rs = st.executeQuery(consulta);
            String id = null;
            while (rs.next()){
                Object[] fila = {rs.getString(1),
                rs.getString(2),
                rs.getString(3),
                rs.getString(4),
                rs.getString(5),
                rs.getString(6)};
                if(rs.getString(5).matches("Tarjeta")){
                    totalTar = totalTar + Double.parseDouble(rs.getString(2));
                }else{
                    totalCon = totalCon + Double.parseDouble(rs.getString(2));
                }
                dtmVentas.addRow(fila);
                cant = cant +1;
            }
            total = totalTar + totalCon;
        } catch (Exception e){
            e.printStackTrace();
        }
        getVentaListar().getjLabelTargeta().setText(totalTar+"");
        getVentaListar().getjLabelContado().setText(totalCon+"");
        getVentaListar().getjTextFieldCantidadVentas().setText(cant+"");
        getVentaListar().getjTextFieldTotalVendido().setText(total+"");
        Gastos.gastosListar a = new Gastos.gastosListar();
        a.getVentana().dispose();
        double aux = a.actualizarPorCampo(FechaD, FechaH);
        getVentaListar().getjLabelgastoefec().setText(aux+"");
        getVentaListar().getjLabeldTotalCaja().setText(totalCon-aux+"");
        getVentaListar().getjTableVenta().setModel(dtmVentas);
        conectar.cerrar();
    }

    public void actionPerformed(ActionEvent e) {
        int select = getVentaListar().getjTableVenta().getSelectedRow();
        if (e.getSource() == getVentaListar().getjButtonMostrarVenta()){
            if (this.factura == null){
                if(select!=-1){
                    factura = new Ventas.FacturaGUI();
                    armarFactura(select);
                    factura.setVisible(true);
                }else {
                    JOptionPane.showMessageDialog(null, "Debe seleccionar un elemento", "Error por seleccion nula", JOptionPane.ERROR_MESSAGE);
                }
            } else {
                if(select!=-1){
                    armarFactura(select);
                    factura.setVisible(true);
                }else {
                    JOptionPane.showMessageDialog(null, "Debe seleccionar un elemento", "Error por seleccion nula", JOptionPane.ERROR_MESSAGE);
                }
            }          
        } else if (e.getSource() == getVentaListar().getjButtonMostrarTodos()){
            actualizarTabla();
            getVentaListar().getjTextFielDesdeFecha().setText("");
            getVentaListar().getjTextFieldHastaFecha().setText("");
        } else if (e.getSource() == getVentaListar().getjButtonEliminar()){
            eliminar(select);
        } else if (e.getSource() == getVentaListar().getjButtonMostrarFecha()){
            String fechad = getVentaListar().getjTextFielDesdeFecha().getText();
            String fechah =getVentaListar().getjTextFieldHastaFecha().getText();
            if(esFecha(fechad) & esFecha(fechah)){
                actualizarPorFecha(fechad,fechah);
                getVentaListar().getjTextFielDesdeFecha().setText("");
                getVentaListar().getjTextFieldHastaFecha().setText("");
            }else{
                JOptionPane.showMessageDialog(null, "Ingrese fecha dd/mm/aaaa", "Fecha Nula", JOptionPane.WARNING_MESSAGE);
            }

        } if (e.getSource() == getVentaListar().getjButtonSalir()){
            getVentaListar().dispose();
        }
    }

    public boolean esFecha(String fech){
        Pattern p;
        p = Pattern.compile("^(31|30|2[0-9]{1}|1[0-9]{1}|0[1-9]{1})/(0[1-9]{1}|1[0-2]{1})/[0-9]{4}$");
        Matcher m = p.matcher(fech);
        return m.matches();
    }

    private void eliminar(int select){
        if (select != -1){
            int a = Integer.parseInt(getVentaListar().getjTableVenta().getValueAt(select, 0).toString());

            conectar.conectar();
            int confirmado = JOptionPane.showConfirmDialog(null,"¿Está seguro que desea eliminar el La Venta?", "Eliminar Venta", JOptionPane.YES_NO_OPTION);

            if (JOptionPane.OK_OPTION == confirmado){
                try {
                    Statement st = conectar.getConn().createStatement();
                    System.out.println(a);
                    String borrar = "DELETE FROM \"Ventas\" WHERE \"IDVenta\" = '"+a+"';";
                    System.out.println(st.execute(borrar));
                    st.close();
                } catch (Exception ex) {   
                    ex.printStackTrace();
                }
                conectar.cerrar();
                this.actualizarTabla();
                JOptionPane.showMessageDialog(null, "Se ha eliminado la venta", "Venta Eliminada", JOptionPane.INFORMATION_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(null, "Debe seleccionar un elemento", "Error por seleccion nula", JOptionPane.ERROR_MESSAGE);
        }
    }

    public void armarFactura(int select){
        DefaultTableModel dtmArticulof;
        String[] titulos = {"CantArt", "Nombre y marca","$ Precio"};
        Object[][] datos = {};
        dtmArticulof = new DefaultTableModel(datos, titulos);
        if (select != -1){
            int a = Integer.parseInt(getVentaListar().getjTableVenta().getValueAt(select, 0).toString());
            System.out.println(a);
            conectar.conectar();
            try {
            //----------Armo prinsipal-------------
                String consulta = "SELECT * FROM \"Ventas\" WHERE \"IDVenta\"='"+a+"';" ;
                Statement st = conectar.getConn().createStatement();
                ResultSet rs = st.executeQuery(consulta);
                String tipopag = null;
                while (rs.next()){
                    factura.getjTextPaneTotal().setText(rs.getString(2));
                    factura.getjTextPaneCantidadArt().setText(rs.getString(3));
                    factura.getjTextPaneFecha().setText(rs.getString(4));
                    factura.getjTextPaneTipoPago().setText(rs.getString(5));
                    factura.getjTextPaneUsuario().setText(rs.getString(6));
                    tipopag = rs.getString(5);

                }
                String consulta1 = "SELECT * FROM \"TipoPago\" WHERE \"Tipo\" = '"+tipopag+"';";
                rs = st.executeQuery(consulta1);
                double dob=0;
                while (rs.next()){
                    dob = rs.getDouble(2);
                }
                //---------Inserto articulos en la tabla-------------------
                consulta = "SELECT \"Cant\" ,\"nombre\",\"marca\" ,\"precioCosto\" FROM \"Ventas\" v, \"Facturacion\" f, \"Articulo\" a WHERE  v.\"IDVenta\" ="+a+" AND v.\"IDVenta\" = f.\"IDVentas\" AND f.\"CodigoArt\" = a.\"codArt\";" ;
                rs = st.executeQuery(consulta);
                while (rs.next()){
                    Object[] fila = {rs.getString(1),
                    rs.getString(2)+" "+rs.getString(3),
                    rs.getDouble(4)*dob};
                    dtmArticulof.addRow(fila);
                    
                }
                factura.getjTableArticulos().setModel(dtmArticulof);
            //----------------------------
                st.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            conectar.cerrar();
        
        } 
    }

    public void sumaContadoTarjeta(){

    }

    public void keyTyped(KeyEvent e) {

    }

    public void keyPressed(KeyEvent e) {   }

    public void keyReleased(KeyEvent e) {   }

    public void setVisible(boolean b) {
        getVentaListar().setVisible(b);
    }

    /**
     * @return the unaVenta
     */
    public Ventas.GUIVenta getUnaVenta() {
        return unaVenta;
    }

    /**
     * @return the ventaListar
     */
    public ventasListar getVentaListar() {
        return ventaListar;
    }

    
}
